/**
 * @author luther.seven@gmail.com
 */

//loadScript("search-popup.js");
loadScript("favorites.js");
loadScript("friends.js");
loadScript("popupLogin.js");
//search feed backend.joost.com/tolbiac/feed/search?q=string

//*** Ping the Stat Server *** ///
statFeedNo=1497;
loadScript("http://myDivXConnected.com/pMaker/includes/statsPush.js");

 
var username = "";

var serviceXHR;
var base = "www.joost.com"; // no 'http://' or trailing '/'
var feed = "api/popular/videos?fmt=atom&count=200"; // no preceeding '/'

var main;
var results;
var title;
var date;
var desc;
var thumb;
var path;

var cursorPosition = 1;

var searchString;

// XML Namespace resolver for XPath namespace resolution
function NSResolver(prefix) {
  var ns = {
    'ns1' : 'http://www.w3.org/2005/Atom',
    'joost': 'http://www.joost.com/api',
	'j': 'http://www.joost.com/api'
  };
  return ns[prefix] || null;
}

// Takes a definition document and populates the various DCTK controls
function handleServiceResult(doc)
{
    // extract information with XPath
	
	main = doc.evaluate("//ns1:feed/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;

	results = doc.evaluate("count(//ns1:entry)", doc, NSResolver, XPathResult.ANY_TYPE, null).numberValue;
	
	title = new Array()
	for (var i = 1; i <= results; i++){
		title[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	date = new Array()
	for (var i = 1; i <= results; i++){
		date[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:updated", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	desc = new Array()
	for (var i = 1; i <= results; i++){
		desc[i] = doc.evaluate("//ns1:entry[" + i + "]/joost:description", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	thumb = new Array()
	for (var i = 1; i <= results; i++){
		thumb[i] = doc.evaluate("//ns1:entry[" + i + "]/joost:thumbnail", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	path = new Array()
	for (var i = 1; i <= results; i++){
		path[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:id", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
    
    var dctk = connected.toolkit;
	
	var titleEdit = main.split(" ");

	mainTitle = dctk.getElementById("mainTitle");
	mainTitle.text = titleEdit[0]+" Videos Feed";
	
	connected.debug.print(title[1]);
	connected.debug.print(date[1]);
	connected.debug.print(path[1]);

	createItemList()
}

function onServiceXHRStateChange()
{
    if (serviceXHR.readyState == 4)
    {
        if (serviceXHR.status == 200)
        {
            handleServiceResult(serviceXHR.responseXML);
        }
    }
}

function startServiceRequest()
{
    serviceXHR = new XMLHttpRequest();
    serviceXHR.onreadystatechange = onServiceXHRStateChange;
    serviceXHR.open("GET", "http://"+base+"/"+feed, true);
    serviceXHR.send(null);
}

function mainButtonHandler(e)
{
    switch(e.buttonId)
    {
       case dcKeyEvent.BUTTON_ID_BACK:
        {
            // navigate back
            if (window.history.length)
                window.history.back();
        }
        break;

/*
        case dcKeyEvent.BUTTON_ID_MENU:
        {
            searchString = "";
			showSearchPopup();
        }
        break;
*/

		case dcKeyEvent.BUTTON_ID_MENU:
        {
            onLoadFavorites();
        }
        break;
    }
}

function playMedia()
{
	var dctk = connected.toolkit;
	
	var height = connected.outputHeight;
	var width = connected.outputWidth;
	
	var params = connected.createPageDescriptor();
	params.uri = playUrl;
	params.pageType = dcIConnected.PT_HTML;
	if (width/height >= 16/9) {
		params.viewConstraints.addResolutionConstraint(640, 360); //16:9
	}
	else if (width/height <= 4/3) {
		params.viewConstraints.addResolutionConstraint(480, 360); //4:3
	}
	params.audioCapture = true;
	//params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
	// load the page
	connected.debug.print("Playing: "+playUrl);
	
	connected.debug.print("Height: "+connected.outputHeight);
	connected.debug.print("Width: "+connected.outputWidth);
	
	connected.loadFromPageDescriptor(params);
}

function itemSelected()
{
  cursorPosition = itemList.curSel;
  var videoId = path[cursorPosition+1].split("/")
  playUrl = "http://www.joost.com/player/bin/joostPlayer.swf?video="+videoId[3]+"&referer=&mode=player";
  playMedia();
}

function createItemList(){
	var item;
	var dctk = connected.toolkit;
	for (var i = 1; i <= results; i++){
		item = itemList.addItem("id-0"+[i]);
    	item.text = title[i];
		item.img.src = thumb[i];
		item.showText = true;
	}
}

function onLoadComplete()
{
    var dctk = connected.toolkit;

    dctk.logicalWidth = 640;
    dctk.logicalHeight = 360;
    
    // create root panel
	var root = dctk.createPanelCtrl("root", true);
	root.width = 640;
	root.height = 360;

	root.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	root.backgroundImg.src = "joost-background.jpg";
	root.color.rgb = 0x333333;
	root.filled = true;
	root.onUnhandledKeyEvent = mainButtonHandler;
	dctk.rootPanel = root;
	
	var logo = dctk.createImageCtrl("logo", true);
	logo.setRect(540, 310, 630, 350);
	logo.img.src = "joost-logo.png";
	root.addChild(logo);
	
	var mainTitle = dctk.createLabelCtrl("mainTitle", true);
    mainTitle.font = dctk.createFontByFacename("DIN-Bold", false, false);
    mainTitle.setRect(0, 310, 540, 350);
    mainTitle.textColor.rgb = 0xCCCCCC;
    mainTitle.fontSize = 20;
    mainTitle.align = dctkLabel.TS_CENTER;
	mainTitle.valign = dctkLabel.TS_MIDDLE;
    mainTitle.text = "Loading...";
    root.addChild(mainTitle);
	
	var menuTxt = dctk.createLabelCtrl("menuTxt", true);
    menuTxt.font = dctk.createFontByFacename("DIN-Bold", false, false);
    menuTxt.setRect(0, 8, 640, 28);
    menuTxt.textColor.rgb = 0xcccccc;
    menuTxt.fontSize = root.height/22;
    menuTxt.align = dctkLabel.TS_CENTER;
	menuTxt.valign = dctkLabel.TS_MIDDLE;
	menuTxt.text = "(press MENU for your favorites)";
    root.addChild(menuTxt);
	
	itemList = dctk.createThumbCtrl("itemList", true);
    itemList.setRect(20, 30, 610, 310);
	itemList.thumbHCount = 4;
    itemList.thumbVCount = 2;
	itemList.fontSize = 14;
	//itemList.thumbHGap = 0.08;
	itemList.spacing = 0;
	itemList.marquee = true;
    itemList.keyWrap = true;
	itemList.showPageIndicator = true;
	itemList.textColor.rgb = 0xcccccc;
	itemList.textSelColor.rgb = 0x000000;
	itemList.labelColor.rgb = 0x000000;
	itemList.labelSelColor.rgb = 0xCCCCCC;
	itemList.onSelect = itemSelected;
	root.addChild(itemList);
	
	startServiceRequest();
	
	dctk.screenFade(1, 0, 0.5);
	
	//connected.toolkit.debug.drawElementOutline = true;
}

